<template>
  <div>
    <!-- 操作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="danger"
          :icon="Delete"
          @click="handleDelete"
          :disabled="multiple"
          >删除</el-button
        >
      </el-form-item>
      <el-form-item prop="keywords">
        <el-input
          v-model="queryParams.keywords"
          placeholder="标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作栏 -->

    <!-- 数据展示表格 -->
    <el-table
      v-loading="loading"
      :data="advertList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" min-width="5" align="center" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="title" min-width="100" label="广告标题" />
      <el-table-column label="广告图片" width="100">
        <template #default="scope">
          <el-popover placement="right" trigger="hover">
            <el-image :src="scope.row.picUrl" />
            <template #reference>
              <img
                :src="scope.row.picUrl"
                style="max-height: 60px; max-width: 60px"
              />
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="开始时间" width="150" />
      <el-table-column prop="endTime" label="结束时间" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">开启</el-tag>
          <el-tag v-else type="info">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            plain
            @click.stop="handleUpdate(scope.row)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            plain
            @click.stop="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 数据展示表格 -->

    <!-- 枫叶 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :small="false"
      :disabled="false"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 枫叶 -->

    <!-- 表单弹出框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px">
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>

        <el-form-item label="有效期">
          <el-date-picker
            v-model="validityPeriod"
            type="daterange"
            range-separator="~"
            start-placeholder="起始时间"
            end-placeholder="截止时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="广告图片" prop="picUrl">
          <Upload v-model="formData.picUrl" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" style="width: 200px" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="跳转链接" prop="url">
          <el-input v-model="formData.url" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="formData.remark" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 表单弹出框 -->
  </div>
</template>

<script setup lang="ts">
import {
  listAdvertPages,
  getAdvertForm,
  updateAdvert,
  addAdvert,
  deleteAdverts,
} from "@/api/sms/advert";
import Upload from "@/components/Upload/index.vue";
import { Advert, AdvertForm, AdvertQuery } from "@/api/sms/advert/types";
import { Delete, Search, Plus, Refresh, Edit } from "@element-plus/icons-vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, toRefs, ref } from "vue";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: true,
  // 选中ID数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: { pageNum: 1, pageSize: 10 } as AdvertQuery,
  advertList: [] as Advert[],
  total: 0,
  dialog: { title: "", visible: false } as any,
  formData: {
    status: 1,
    sort: 100,
  } as AdvertForm,
  rules: {
    title: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
    picUrl: [{ required: true, message: "请上传广告图片", trigger: "blur" }],
  },
  validityPeriod: "" as any,
});

const {
  loading,
  multiple,
  queryParams,
  advertList,
  total,
  dialog,
  formData,
  rules,
  validityPeriod,
} = toRefs(state);

/* 查询 */
const handleQuery = async () => {
  state.loading = true;
  let {
    data: { data },
  }: any = await listAdvertPages(state.queryParams);
  console.log(data);
  state.advertList = data.list;
  state.total = data.total;
  state.loading = false;
};
/* 查询 */

/* 重置 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};
/* 重置 */

/* 按钮和复选框 */
const handleSelectionChange = (selection: any) => {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
};
/* 按钮和复选框 */

/* 添加 */
const handleAdd = () => {
  state.dialog = {
    title: "添加广告",
    visible: true,
  };
};
/* 添加 */

/* 修改 */
const handleUpdate = (row: any) => {
  state.dialog = {
    title: "修改广告",
    visible: true,
  };
  const advertId = row.id || state.ids;
  getAdvertForm(advertId).then(({ data: { data } }: any) => {
    state.formData = data;
    validityPeriod.value = [data.beginTime, data.endTime];
  });
};
/* 修改 */

/* 表单提交 */
const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      const avertId = state.formData.id;
      if (avertId) {
        updateAdvertHelper(avertId);
      } else {
        addAdvertHelper();
      }
    }
  });
};

const updateAdvertHelper = (avertId: number) => {
  // 有效期转换
  if (validityPeriod.value) {
    formData.value.beginTime = validityPeriod.value[0];
    formData.value.endTime = validityPeriod.value[1];
  }

  updateAdvert(avertId, state.formData).then(() => {
    ElMessage.success("修改成功");
    cancel();
    handleQuery();
  });
};

const addAdvertHelper = () => {
  addAdvert(state.formData).then(() => {
    ElMessage.success("新增成功");
    cancel();
    handleQuery();
  });
};
/* 表单提交 */

/* 重置表单 */
const cancel = () => {
  state.formData.id = undefined;
  dataFormRef.value.resetFields();
  state.dialog.visible = false;
};
/* 重置表单 */

/* 删除表单 */
const handleDelete = async (row: any) => {
  const ids = `${row.id || state.ids}`;
  try {
    await ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await deleteAdverts(ids);
    ElMessage.success("删除成功");
    handleQuery();
  } catch {
    ElMessage.info("已取消删除");
  }
};
/* 删除表单 */

/* 分页 */
const handleSizeChange = (val: number) => {
  handleQuery();
};
const handleCurrentChange = (val: number) => {
  handleQuery();
};
/* 分页 */
onMounted(() => {
  handleQuery();
});
</script>

<style scoped lang="less">
.el-pagination {
  margin: 20px 0px 0px 20px;
}
</style>
